package com.zpkj.portal.third.jpush;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.common.resp.DefaultResult;
import cn.jpush.api.device.AliasDeviceListResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 极光推送工具类
 *
 * @author xc
 *         2016年4月27日 下午6:12:58
 */
public class JPushUtils {

    protected static final Logger logger = LoggerFactory.getLogger(JPushUtils.class);
    //极光平台配置的appKey-最开始的app1
    private static final String jiguang_appKey_1 = "b0e4001ab78966c38496531a";
    //极光平台配置的masterSecret
    private static final String jiguang_masterSecret_1 = "12bd422c124857a0db234209";
    //极光平台配置的appKey-新的苹果app2
    private static final String jiguang_appKey_2 = "ad8d8066b1ad09f64f075729";
    //极光平台配置的masterSecret
    private static final String jiguang_masterSecret_2 = "9cc644c39f0301ca7092a1b3";

    private static JPushClient jpushClient_1 = new JPushClient(jiguang_masterSecret_1, jiguang_appKey_1);

    private static JPushClient jpushClient_2 = new JPushClient(jiguang_masterSecret_2, jiguang_appKey_2);
    /*
    // 新账号1、新账号2
    //极光平台配置的appKey-最开始的app1
    private static final String jiguang_appKey_n1 = "65a5cc3c804b0b9deeefaf58";
    //极光平台配置的masterSecret
    private static final String jiguang_masterSecret_n1 = "51ba15269f279812abd21819";
    //极光平台配置的appKey-新的苹果app2
    private static final String jiguang_appKey_n2 = "25e81b0fba810ba5118ecc5c";
    //极光平台配置的masterSecret
    private static final String jiguang_masterSecret_n2 = "b60d12d31cf8c768bb975dcf";

    private static JPushClient jpushClient_n1 = new JPushClient(jiguang_masterSecret_n1, jiguang_appKey_n1);

    private static JPushClient jpushClient_n2 = new JPushClient(jiguang_masterSecret_n2, jiguang_appKey_n2);
    */

//	public static void main(String[] args) throws APIConnectionException, APIRequestException {
////		MeesageContent mc = new MeesageContent();
////		mc.setCode(3);
////		mc.setTitle("更新提示");
////		mc.setCodeInfo("更新提示");
//		String content="来玩啊,骚年1!";
//		String tagName = "ad60c2142cd8429281b47b4e82490b02";
//		String registrationId = "13065ffa4e00a212e60";
//		String alias = "d09d034229d24d26a43c8a3b9f1735a8";
////		pushNoticeToAll(0,"prod",content,"","","");
//        getAliasDeviceList("c2d29babe9924444a18637e78063da94");
//	}

    public static void sendPush(PushPayload payload) {
        try {
            PushResult result1 = jpushClient_1.sendPush(payload);
            logger.info("app1的推送结果：：：" + result1.isResultOK());
        } catch (Exception a) {
            logger.info(a.getMessage());
        }
        try {
            PushResult result2 = jpushClient_2.sendPush(payload);
            logger.info("app2的推送结果：：：" + result2.isResultOK());
        } catch (Exception b) {
            logger.info(b.getMessage());
        }
        /*
        // 新账号1、2
        try {
            PushResult resultn1 = jpushClient_n1.sendPush(payload);
            logger.info("appn1的推送结果：：：" + resultn1.isResultOK());
        } catch (Exception a) {
            logger.info(a.getMessage());
        }
        try {
            PushResult resultn2 = jpushClient_n2.sendPush(payload);
            logger.info("appn2的推送结果：：：" + resultn2.isResultOK());
        } catch (Exception b) {
            logger.info(b.getMessage());
        }
       */ 
    }

    /**
     * 给所有用户发通知
     *
     * @param content 消息内容
     */
    public static void pushNoticeToAll(int deviceType, String environment, String content,
                                       String extraKey, String extraContent, String title) throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
        logger.info("给所有用户发推送,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.all())
                    .setNotification(
                            Notification.newBuilder()
                                    .setAlert(content)
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .setTitle(title)
                                            .addExtra(extraKey, extraContent).build())
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setSound("default")
                                            .addExtra(extraKey, extraContent).build())
                                    .build()
                    )
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setNotification(
                            Notification.newBuilder()
                                    .setAlert(content)
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .setTitle(title)
                                            .addExtra(extraKey, extraContent).build())
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setSound("default")
                                            .addExtra(extraKey, extraContent).build())
                                    .build()
                    )
                    .setAudience(Audience.all())
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 给IOS和安卓 按标签发送通知
     *
     * @param content 消息内容
     * @param tagName 标签组名称
     */
    public static void pushNoticeByTag(String environment, String tagName,
                                       String content, String extraKey, String extraContent, String title)
            throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
        PushPayload payload = null;
        logger.info("按标签发推送,极光推送当前环境===" + environment);
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.tag(tagName))
                    .setNotification(
                            Notification.newBuilder()
                                    .setAlert(content)
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .addExtra(extraKey, extraContent).build())
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setSound("default")
                                            .addExtra(extraKey, extraContent).build())
                                    .build()
                    )
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
            //测试环境
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.tag(tagName))
                    .setNotification(Notification.newBuilder()
                            .setAlert(content)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .addExtra(extraKey, extraContent).build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .setSound("default")
                                    .addExtra(extraKey, extraContent).build())
                            .build()
                    )
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 给IOS和安卓 按别名发送通知
     *
     * @param content 消息内容
     * @param alias   别名
     */
    public static void pushNoticeByAlias(String environment, String alias, String content, String extraKey, String extraContent, String title)
            throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
//    	JPushClient jpushClient = new JPushClient(masterSecret, appKey, null,config);
        logger.info("按别名发送通知,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.alias(alias))//分发类型
                    .setNotification(
                            Notification.newBuilder()
                                    .setAlert(content)
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .addExtra(extraKey, extraContent).build())
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setSound("default")
                                            .addExtra(extraKey, extraContent).build())
                                    .build()
                    )
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.alias(alias))//分发类型
                    .setNotification(
                            Notification.newBuilder()
                                    .setAlert(content)
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .addExtra(extraKey, extraContent).build())
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setSound("default")
                                            .addExtra(extraKey, extraContent).build())
                                    .build()
                    )
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 给IOS和安卓 按设备id发送通知
     *
     * @param content        消息内容
     * @param registrationId 设备id
     */
    public static void pushNoticeById(String environment, String registrationId, String content, String extraKey, String extraContent, String title) {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
//    	JPushClient jpushClient = new JPushClient(masterSecret, appKey, null,config);
        logger.info("按设备id发通知,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.registrationId(registrationId))//分发类型
                    .setNotification(Notification.newBuilder()
                            .setAlert(content)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(title)
                                    .addExtra(extraKey, extraContent).build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .setSound("default")
                                    .addExtra(extraKey, extraContent).build())
                            .build())
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.registrationId(registrationId))//分发类型
                    .setNotification(Notification.newBuilder()
                            .setAlert(content)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(title)
                                    .addExtra(extraKey, extraContent).build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .setSound("default")
                                    .addExtra(extraKey, extraContent).build())
                            .build())
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 给所有用户发透传
     *
     * @param content 消息内容
     */
    public static void pushMessageToAll(String environment, String content) throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
        logger.info("给所有用户发透传,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setMessage(Message.content(content))
                    .setAudience(Audience.all())
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setMessage(Message.content(content))
                    .setAudience(Audience.all())
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 给IOS和安卓 按标签发送透传
     *
     * @param content 消息内容
     * @param tagName 标签组名称
     */
    public static void pushMessageByTag(String environment, String tagName, String content, String title) throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
        logger.info("按标签透传,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.tag(tagName))
//                    .setNotification(Notification.alert(content))
                    .setMessage(Message.content(content))
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.tag(tagName))
//                    .setNotification(Notification.alert(content))
                    .setMessage(Message.content(content))
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 按id透传
     */
    public static void pushMessageById(String environment, String registrationId, String content, String title) throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
        logger.info("按设备id透传,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.registrationId(registrationId))//分发类型
//                    .setNotification(Notification.alert(content))//消息
                    .setMessage(Message.content(content))//透传
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.registrationId(registrationId))//分发类型
//                    .setNotification(Notification.alert(content))//消息
                    .setMessage(Message.content(content))//透传
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 按别名透传
     *
     * @param content
     * @return
     * @throws APIConnectionException
     * @throws APIRequestException
     */
    public static void pushMessageByAlias(String environment, String alias, String content, String title) throws APIConnectionException, APIRequestException {
        ClientConfig config = ClientConfig.getInstance();
        config.setTimeToLive(0);//消息离线有效时间
        logger.info("按别名透传,极光推送当前环境===" + environment);
        PushPayload payload = null;
        //生产环境
        if ("prod".equals(environment)) {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
//                    .setAudience(Audience.registrationId(registrationId))
                    .setAudience(Audience.alias(alias))//分发类型
//                    .setNotification(Notification.alert(content))//消息
                    .setMessage(Message.content(content))//透传
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())//平台
                    .setAudience(Audience.alias(alias))//分发类型
//                    .setNotification(Notification.alert(content))//消息
                    .setMessage(Message.content(content))//透传
//                    .setOptions(Options.newBuilder().setApnsProduction(true).build())//设置成生产
                    .build();
        }
        sendPush(payload);
    }

    /**
     * 给某个设备增加 别名和添加组、删除组
     *
     * @param registration_id 设备id
     * @param alias           别名
     * @param tagsToAdd       要加入的标签Set<String>
     * @param tagsToRemove    要删除的标签Set<String>
     */
    public static int updateDeviceTagAlias(
            String registration_id, String alias,
            Set<String> tagsToAdd, Set<String> tagsToRemove){
        int pushStatus=1;
        try {
            DefaultResult result1 = jpushClient_1.updateDeviceTagAlias(registration_id, alias, tagsToAdd, tagsToRemove);
            logger.info("app1添加别名和组的结果：：：" + result1.isResultOK());
            pushStatus=0;
        } catch (Exception a) {
            logger.info("app1添加别名和组的异常：：：" + a.getMessage());
        }
        try {
            DefaultResult result2 = jpushClient_2.updateDeviceTagAlias(registration_id, alias, tagsToAdd, tagsToRemove);
            logger.info("app2添加别名和组的结果：：：" + result2.isResultOK());
            pushStatus=0;
        } catch (Exception b) {
            logger.info("app2添加别名和组的异常：：：" + b.getMessage());
        }
        /*
        // 新账号1、2
        try {
            DefaultResult resultn1 = jpushClient_n1.updateDeviceTagAlias(registration_id, alias, tagsToAdd, tagsToRemove);
            logger.info("appn1添加别名和组的结果：：：" + resultn1.isResultOK());
            pushStatus=0;
        } catch (Exception a) {
            logger.info("appn1添加别名和组的异常：：：" + a.getMessage());
        }
        try {
            DefaultResult resultn2 = jpushClient_n2.updateDeviceTagAlias(registration_id, alias, tagsToAdd, tagsToRemove);
            logger.info("appn2添加别名和组的结果：：：" + resultn2.isResultOK());
            pushStatus=0;
        } catch (Exception b) {
            logger.info("appn2添加别名和组的异常：：：" + b.getMessage());
        }
        */
        return pushStatus;
    }

    /**
     * 根据设备id获取别名、标签信息
     */
//	public static void getDeviceTagAlias(String registionId) throws APIConnectionException, APIRequestException {
//		TagAliasResult result = jpushClient.getDeviceTagAlias(registionId);
//	} 

    /**
     * 根据别名获取设备列表信息
     *
     * @throws APIRequestException
     * @throws APIConnectionException
     */
    public static List<String> getAliasDeviceList(String alias) {
        List<String> list = new ArrayList<String>();
        try {
        	AliasDeviceListResult result1 = jpushClient_1.getAliasDeviceList(alias, null);
            if (result1.registration_ids != null) {
                list.addAll(result1.registration_ids);
            }
            AliasDeviceListResult result2 = jpushClient_2.getAliasDeviceList(alias, null);
            if (result2.registration_ids != null) {
                list.addAll(result2.registration_ids);
            }
            /*
            // 新账号1、2
        	AliasDeviceListResult resultn1 = jpushClient_n1.getAliasDeviceList(alias, null);
            if (Collections3.isNotEmpty(resultn1.registration_ids)) {
                list.addAll(resultn1.registration_ids);
            }
            AliasDeviceListResult resultn2 = jpushClient_n2.getAliasDeviceList(alias, null);
            if (Collections3.isNotEmpty(resultn2.registration_ids)) {
                list.addAll(resultn2.registration_ids);
            }
            */
        } catch (APIConnectionException e) {
            logger.info("***** pushNoticeByTag：极光推送连接异常,推送失败 connection error,JPush push fail *****");
        } catch (APIRequestException e) {
            logger.info("***** pushNoticeByTag：极光推送请求异常,推送失败 request error,JPush push fail *****");
        }
        return list;
    }

    /**
     * 清理设备的标签、别名信息
     *
     * @param registionId
     * @throws APIConnectionException
     * @throws APIRequestException
     */
    public static void clearTagAndAlias(String registionId) {
        try {
            DefaultResult result1 = jpushClient_1.updateDeviceTagAlias(registionId, true, true);
            logger.info("app1清理设备的标签、别名信息的结果：：：" + result1.isResultOK());
        } catch (Exception a) {
            logger.info("app1清理设备的标签、别名信息异常：：：" + a.getMessage());
        }
        try {
            DefaultResult result2 = jpushClient_2.updateDeviceTagAlias(registionId, true, true);
            logger.info("app2清理设备的标签、别名信息的结果：：：" + result2.isResultOK());
        } catch (Exception b) {
            logger.info("app2清理设备的标签、别名信息异常：：：" + b.getMessage());
        }
        /*
        //新账号1、2
        try {
            DefaultResult resultn1 = jpushClient_n1.updateDeviceTagAlias(registionId, true, true);
            logger.info("appn1清理设备的标签、别名信息的结果：：：" + resultn1.isResultOK());
        } catch (Exception a) {
            logger.info("appn1清理设备的标签、别名信息异常：：：" + a.getMessage());
        }
        try {
            DefaultResult resultn2 = jpushClient_n2.updateDeviceTagAlias(registionId, true, true);
            logger.info("appn2清理设备的标签、别名信息的结果：：：" + resultn2.isResultOK());
        } catch (Exception b) {
            logger.info("appn2清理设备的标签、别名信息异常：：：" + b.getMessage());
        }
        */
    }
}
